package org.opens.javaskill.jackson.xml;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 说明:
 *      1. JacksonXmlRootElement表示声明生成的xml的主节点名称
 */
@Data
//@JacksonXmlRootElement(localName = "XmlObj")
public class XmlObj {

    private static Random random = new Random();

    /**
     * 说明:
     *      1. @JacksonXmlProperty用来声明当前节点的名称
     */
    //@JacksonXmlProperty(localName = "Id")
    //@JacksonXmlCData
    private Integer id;

    //@JacksonXmlProperty(localName = "Name")
    private String name;

    /**
     * 说明:
     *      1. @JacksonXmlCData只能作用于String类型的字段, 因为只有String类型的变量才会容纳特殊字符.
     */
    //@JacksonXmlProperty(localName = "Salary")
    //@JacksonXmlCData
    private Double salary;

    //@JacksonXmlProperty(localName = "Birthday")
    private Date birthday;

    /**
     * 说明:
     *      1. 特殊的集合字段需要@JacksonXmlElementWrapper注解来声明;
     *          - List中的元素用@JacksonXmlProperty声明.
     */
    //@JacksonXmlElementWrapper(localName = "Scores")
    //@JacksonXmlProperty(localName = "Score")
    private List<Score> scores;

    public static XmlObj init() {
        XmlObj obj = new XmlObj();
        obj.setId(random.nextInt(1000));
        obj.setName("xml" + random.nextInt(1000));
        obj.setBirthday(new Date());
        obj.setSalary(random.nextDouble());
        obj.setScores(Score.getList(3));
        obj.setIgnore("忽略字段");
        return obj;
    }

    /**
     * 说明:
     *      1. @JsonIgnore虽然是json相关的注解, 但是在生成xml时依然适用.
     */
    @JsonIgnore
    private String ignore;

    @Data
    public static class Score {

        private static Random random = new Random();

        private String name;

        private Double value;

        public static Score init() {
            Score score = new Score();
            score.setName("s" + random.nextInt(1000));
            score.setValue(random.nextDouble());
            return score;
        }

        public static List<Score> getList(int size) {
            List<Score> list = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                list.add(init());
            }
            return list;
        }

    }

}
